 package pl.edu.agh.portal.application.portlets;

import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.apache.jetspeed.login.LoginConstants;
import org.apache.portals.bridges.common.GenericServletPortlet;

import pl.edu.agh.portal.application.utils.PortletsUtils;
import pl.edu.agh.thesis.webservices.employee.client.EmployeeUtils;

public class LoginPortlet extends GenericServletPortlet {


	private static final String NORMAL_VIEW = "/login_portlet.jsp";
	
	private PortletRequestDispatcher normalView;
	
	// 0 - no login; 1 - invalid; 2 - valid login
	private int status = 0;	
	
	public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {		
		PortletPreferences preferences = request.getPreferences();
		
		switch (status) {
		case 0:
			preferences.setValue(PortletsUtils.LOGIN_STATUS, PortletsUtils.NO_LOGIN);
			break;
		case 1:
			preferences.setValue(PortletsUtils.LOGIN_STATUS, PortletsUtils.INVALID_LOGIN);
			break;			
		default:
			break;
		}
		status = 0;	
		request.setAttribute("HideDecorator", new Boolean(true)) ;
		normalView.include(request, response);		
	}
		
	
	@Override
	public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
		String username = request.getParameter(LoginConstants.USERNAME);
		String password = request.getParameter(LoginConstants.PASSWORD);
		
		String session = EmployeeUtils.login(username, password);
		
		if ((session == null) || (session != null && session.length() == 0)) {
			status = 1;
		} else if (session.length() > 0){
			status = 0;	
			PortletsUtils.temp_session = session;
		}
			
		if (status == 0) {
			String redirectLocation = "/portal/login/proxy" 
	        	+ "?org.apache.jetspeed.login.destination=/portal/portal/user_main_page.psml" 
	        	+ "&" + LoginConstants.USERNAME + "=" + username + "&" + LoginConstants.PASSWORD + "=" + password;
			
			status = 1;			
			response.sendRedirect(redirectLocation);
		} else {
			response.setPortletMode(PortletMode.VIEW);
		}
	}
		
	public void init(PortletConfig config) throws PortletException {
		super.init(config);		
		normalView = config.getPortletContext().getRequestDispatcher(NORMAL_VIEW);		
	}
	
	public void destroy() {
		normalView = null;
		super.destroy();
	}

}
